package com.open.rbac.service.id.impl;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import lombok.RequiredArgsConstructor;

import com.open.center.common.util.CopyUtils;
import com.open.rbac.model.dto.id.IdentityOrganizationRelDto;
import com.open.rbac.model.entity.id.IdentityOrganizationRel;
import com.open.rbac.model.vo.id.IdentityOrganizationRelVo;
import com.open.rbac.service.id.IdentityOrganizationRelService;
import com.open.rbac.service.id.repository.IdentityOrganizationRelRepository;

/**
 * Id组织机构关系服务
 *
 * @author Riche's
 * @since 2025/9/5
 */
@RequiredArgsConstructor
@Service
public class IdentityOrganizationRelServiceImpl implements IdentityOrganizationRelService {

    private final IdentityOrganizationRelRepository identityOrganizationRelRepository;

    @Transactional
    @Override
    public void create(List<IdentityOrganizationRelVo> relVos) {
        List<IdentityOrganizationRel> rels = relVos.stream().map(relVo -> {
            IdentityOrganizationRel rel = new IdentityOrganizationRel();
            rel.setOrganizationId(relVo.getOrganizationId());
            rel.setIdentityId(relVo.getIdentityId());
            return rel;
        }).toList();
        identityOrganizationRelRepository.saveAll(rels);
    }

    @Transactional
    @Override
    public void deleteReallyByIdentityId(String identityId) {
        identityOrganizationRelRepository.deleteReallyByIdentityId(identityId);
    }

    @Override
    public void deleteReallyByIdentityIds(List<String> identityIds) {
        identityOrganizationRelRepository.deleteReallyByIdentityIds(identityIds);
    }

    @Transactional
    @Override
    public void deleteReallyByOrganizationId(String organizationId) {
        identityOrganizationRelRepository.deleteReallyByOrganizationId(organizationId);
    }

    @Override
    public List<IdentityOrganizationRelDto> listIdentityIdIds(List<String> identityIdIds) {
        if (CollectionUtils.isEmpty(identityIdIds)) {
            return List.of();
        }
        return CopyUtils.listCopy(identityOrganizationRelRepository.findIdentityIds(identityIdIds), IdentityOrganizationRelDto.class);
    }

    @Override
    public List<IdentityOrganizationRelDto> listByIdentityIdIds(List<String> identityIdIds) {
        return CopyUtils.listCopy(identityOrganizationRelRepository
            .findByIdentityIdIds(identityIdIds), IdentityOrganizationRelDto.class);
    }
}
